package com.qd.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.DelDTO;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.page.PageUtil;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.domain.entity.cache.CacheOperatorDTO;
import com.qd.common.sys.enums.OperatorType;
import com.qd.system.service.cache.CacheManagerService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * 缓存管理
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/cacheManager")
public class CacheManagerController {
    private final CacheManagerService cacheManagerService;

    /**
     * 根据KEY查询缓存
     */
    @GetMapping(value = "/getById")
    public ApiResultWrapper<CacheOperatorDTO> getById(@Validated @NotBlank(message = "缓存Key不能为空") String key) {
        return cacheManagerService.getStr(key);
    }

    /**
     * 缓存列表
     */
    @GetMapping(value = "/page")
    public Page<CacheOperatorDTO> page(CacheOperatorDTO baseQuery) {
        if (null == baseQuery) {
            throw new ApiException("查询参数不能为空");
        }
        final String key = baseQuery.getKey();
        if(StringUtils.hasLength(key)){
            return cacheManagerService.cachePage(PageUtil.buildPage(baseQuery), baseQuery);
        }
        throw new ApiException("KEY不能为空");
    }

    /**
     * 根据KEY删除缓存
     */
    @PreAuthorize("@ps.hasPermission('system:cache:clear')")
    @DeleteMapping(value = "/deleteByIds")
    @OperatorInfo(title = "根据ID删除缓存", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> deleteByIds(@RequestBody DelDTO<String> delDTO) {
        cacheManagerService.deleteByIds(delDTO.getIds());
        return ApiResult.success("删除成功");
    }

    /**
     * 模糊匹配删除缓存
     */
    @PreAuthorize("@ps.hasPermission('system:cache:clearAll')")
    @DeleteMapping(value = "/matchDeleteById")
    @OperatorInfo(title = "模糊匹配删除缓存", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> matchDeleteById(@RequestBody Map<String, String> map) {
        if (map.isEmpty()) {
            return ApiResult.error("参数不能为空");
        }
        final String key = map.get("key");
        if (StringUtils.hasLength(key)) {
            return cacheManagerService.matchDeleteById(key);
        }
        return ApiResult.error("KEY不能为空");
    }
}